package com.ocean.system.utils;

import java.io.File;
import java.util.Date;

public class DeleteExpiredFile {

   /* public static void deleteExpiredFileTask(String path , int sj) {
        File file = new File(path);
        deleteExpiredFile(file,sj);
    }

    private static void deleteExpiredFile(File file,int sj) {
        if (!file.exists()) return;
        if (!file.isDirectory()) {
            determineExpiredFile(file,sj);
        } else {
            for (File f : file.listFiles()) {
                determineExpiredFile(f,sj);
            }
        }
    }

    private static void determineExpiredFile(File file,int sj) {
        long lastModifiedTime = file.lastModified();
        long currentTime = new Date().getTime();
        //long timeInterval = 30 * 24 * 60 * 60 * 1000;
        long timeInterval = sj * 24 * 60 * 60 * 1000;
        if (currentTime - lastModifiedTime > timeInterval) {
            file.delete();
        }
    }*/
   public static void deleteExpiredFileTask(String path, int sj) {
       File file = new File(path);
       if (!file.exists()) {
           System.err.println("目录不存在：" + path);
           return;
       }
       deleteExpiredFile(file, sj);
       System.out.println("删除过期文件任务完成");
   }

    private static void deleteExpiredFile(File file, int sj) {
        if (!file.exists()) {
            return;
        }
        if (file.isFile()) {
            determineExpiredFile(file, sj);
        } else {
            File[] files = file.listFiles();
            if (files == null) {
                System.err.println("无法访问目录（无权限）：" + file.getAbsolutePath());
                return;
            }
            for (File f : files) {
                deleteExpiredFile(f, sj); // 递归处理子目录
            }
        }
    }

    private static void determineExpiredFile(File file, int sj) {
        long currentTime = System.currentTimeMillis();
        long fileLastModified = file.lastModified();
        long expireThreshold = currentTime - (long) sj * 24 * 60 * 60 * 1000;

        // 调试日志：打印文件信息和时间差（方便排查）
        long diffDays = (currentTime - fileLastModified) / (24 * 60 * 60 * 1000);
        System.out.println("检查文件：" + file.getName() + "，最后修改于 " + diffDays + " 天前");

        if (fileLastModified < expireThreshold) {
            if (file.delete()) {
                System.out.println("已删除：" + file.getAbsolutePath());
            } else {
                System.err.println("删除失败（权限不足或文件被占用）：" + file.getAbsolutePath());
            }
        }
    }

}
